<template>
<div class="online-process bg-white">
  <div class="full-height">
    <!--  搜索区-->
    <div class="form-inline"
         style="justify-content: space-between; padding: 20px 20px 0;flex-basis: initial">
      <div style="display: inline-flex">
        <select-tree label="所在位置" :sel-tree="queryParams.location" class="margin-r-20" ref="selectTree"
                     :tree-list="locationOptions" node-key="hash" @treeChange="_changeTreeNode"/>
        <q-select
          class="select"
          outlined dense emit-value map-options options-dense
          style="height: 32px"
          :options="deviceTypeOptions"
          v-model="queryParams.deviceType"
        >
          <template v-slot:no-option>
            <div class="no-option"/>
          </template>
          <template v-slot:before>
            <span class="form-name">设备类型:</span>
          </template>
        </q-select>
      </div>
      <div style="margin-bottom: 20px;">
        <q-btn class="btn margin-r-10"
               outline
               color="primary"
               label="重置"
               @click="resetSearch" />
        <q-btn class="btn"
               unelevated
               @click="submit"
               color="primary"
               label="查询" />
      </div>
    </div>
    <div class="toolbar form-inline justify-end" style="padding: 0 20px 20px">
      <select-input :list="searchCondition" @search="inputSearch" @clearSearchVal="clearSearchVal" ref="selectInput"/>
    </div>
    <!-- 加工列表 -->
    <template>
      <div class="scroll-area-h">
        <q-scroll-area :thumb-style="thumbStyle" class="full-height">
<!--        <q-scroll-area ref="scrollTargetRef" :thumb-style="thumbStyle" class="full-height">-->
<!--            <q-infinite-scroll   @load="onLoadData" :offset="250" :scroll-target="$refs.scrollTargetRef" >-->
              <div class="list row" style="padding: 0 10px">
                <div class="none-tips text-center font-size-16 full-width" v-show="isNone">暂无数据</div>
                <template v-for="(item,index) in listData">
                  <div class="item-box col-lg-3 col-md-4 col-sm-6" :key="index" v-show="item.runType === 1 || item.runType === '1'">
                    <!--                  <router-link  :to="{path:'/main/program/online-process-detail?planningName='+item.processPlanningName +'&planningNumber='+item.planningNumber +'&deviceName='+item.deviceName +'&deviceName='+item.deviceName}" >-->
                    <div class="list-item shadow-3" @click="routerTo(item)">
                      <div class="item-title text-white row">
                        <div class="name font-size-14 text-weight-bold text-ellipsis">
                          {{item.deviceType}}({{item.deviceNumber}})
                          <q-tooltip>
                            {{item.deviceType}}({{item.deviceNumber}})
                          </q-tooltip>
                        </div>
                      </div>
                      <div class="content">
                        <!--                        <div class="row items-center justify-between">-->
                        <div class="font-size-14 text-ellipsis">
                          在产：{{item.productNamesAndNumbers}}
                          <q-tooltip>{{item.productNamesAndNumbers}}</q-tooltip>
                        </div>
                        <div class="font-size-14 text-ellipsis">工序：{{item.processPlanningName}}
                          <q-tooltip>{{item.processPlanningName}}</q-tooltip>
                        </div>
                        <!--                        </div>-->
                        <div class="row">
                          <div class="run-time font-size-14">运行：{{getTime(item.duration, item.runType)}}</div>
                        </div>
                        <div class="legend row items-center justify-center">
                          <img src="statics/img/gateway.png" class="product">
                          <img src="statics/img/arrow.gif" style="width: 30%">
                          <img src="statics/img/machine.png" class="product">
                        </div>
                        <div class="text-center">当前加工程序：{{item.programNumber}}</div>
                      </div>
                    </div>
                    <!--                  </router-link>-->
                  </div>
                </template>
              </div>
<!--              <template v-slot:loading>-->
<!--                <div class="row justify-center q-my-md">-->
<!--                  <q-spinner-dots color="blue" size="40px" />-->
<!--                </div>-->
<!--              </template>-->
<!--            </q-infinite-scroll>-->
        </q-scroll-area>
      </div>
    </template>
  </div>
</div>
</template>

<script>
import SelectInput from 'src/components/select-input'
import SelectTree from 'src/components/select-tree'
import { getProcessingList, getDeviceTypes } from 'src/boot/program-v2/online'
import refreshMixin from '../../assets/js/refresh-mixin'
import { mapGetters } from 'vuex'
import { getOrganize } from '../../boot/status-monitor/machine'
import { defaultSchemesClearer, diffSecond } from '../../assets/js/util'
import _ from 'lodash'
import moment from 'moment'

export default {
  name: 'online-process',
  mixins: [refreshMixin],
  computed: {
    ...mapGetters([
      'userInfo',
      'client'
    ])
  },
  data () {
    return {
      // 搜索条件
      searchCondition: [{ id: 'number', name: '设备号' }],
      searchBy: '', // 搜索条件 number or name
      keyword: '', // 搜索值
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      listData: [], // 列表数据
      // 所在位置数据源
      locationOptions: [],
      deviceTypeOptions: [],
      queryParams: {
        deviceType: null,
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        } // 所在位置
      },
      isInit: true,
      // 查询定时器
      timerGetList: null,
      timerTime: null,
      isNone: false
      // pagination: {
      //   // 页码
      //   page: 0,
      //   // 每页条数
      //   rowsPerPage: 20
      // },
    }
  },
  created () {
    // 获取组织机构树
    getOrganize().then(res => {
      // 去除 default 节点
      let clearTree = defaultSchemesClearer.clear(res.data)

      // 重新组织 tree
      clearTree.forEach(reorganize)

      function reorganize (node) {
        // 为节点添加唯一键，用于 tree 组件标识唯一节点
        node.uniqueKey = node.level + ':' + node.id

        if (node.children instanceof Array) {
          node.children.forEach(reorganize)
        }
      }

      this.locationOptions = clearTree
      this.queryParams.location = Object.assign({}, clearTree[0])

      this.$refs.selectTree.setValue(this.queryParams.location)

      this._changeTreeNode(this.queryParams.location)
    })
    this.getDeviceTypes()
    // 初始化mqtt
    this.initMqtt()
  },
  mounted () {
    this.timerTime = setInterval(this.updateDuration, 1000)
    this.timerGetList = setInterval(this.getListData, 300000)
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      !vm.isInit && vm.getListData()
    })
  },
  beforeDestroy () {
    // 清除定时器
    clearInterval(this.timerGetList)
    clearInterval(this.timerTime)
    this.closeUbscribeTopic()
  },
  methods: {
    // 获取设备类型
    getDeviceTypes () {
      getDeviceTypes().then(res => {
        const list = res.data.filter(item => item.value !== 'void')
        if (list.length > 0) {
          this.deviceTypeOptions = [{
            value: null,
            label: '全部'
          }]
          this.deviceTypeOptions.push(...list)
        } else {
          this.deviceTypeOptions = []
          this.queryParams.deviceType = ''
        }
      })
    },
    /**
     * 全局刷新数据
     * author: xueli
     */
    refreshInfo () {
      this.resetSearch()
      this.$refs.selectInput.clearValue()
      this.searchBy = ''
      this.keyword = ''
      this.getDeviceTypes()
      this.getListData()
    },
    /**
     * 初始化mqtt
     */
    initMqtt () {
      this.$nextTick(() => {
        if (this.client.connected) {
          this.onConnect()
        } else {
          console.log('websocket未连接')
        }
      })
    },
    /**
     * 接受盒子返回消息
     * @param {string} message
     */
    onMessageArrived (res) {
      const message = JSON.parse(res.body)
      if (!message) {
        console.log('返回res.body为空')
      }
      let msg = message.data
      let msgDeviceId = msg.deviceId
      this.listData.forEach(o => {
        if (o.deviceId + '' === msgDeviceId) {
          o.programNumber = msg.programName
          if (msg.runType && !o.runType) {
            o.time = moment(new Date()).format('YYYY-MM-DD hh:mm:ss')
          }
          o.runType = msg.runType
        }
      })
    },
    /**
     * 订阅并发送消息
     */
    onConnect () {
      console.log('连接开始订阅在线加工')
      this.listData.forEach(o => {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${o.deviceId}`,
          this.onMessageArrived,
          { id: `${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${o.deviceId}` }
        )
      })
      console.log(this.client.subscriptions)
    },
    /**
     * 取消订阅
     */
    closeUbscribeTopic () {
      console.log('取消订阅')
      this.listData.forEach(o => {
        this.client.unsubscribe(`${this.CommonConfig.socketConfig.SOCKET_TOPIC.programName.subscribeTopic}${o.deviceId}`)
      })
    },
    /**
     * FIXME 现在是按定时器每秒增加 应改为当前时间-开始时间
     * 计时器，用来增加每种状态秒数
     */
    updateDuration () {
      this.listData.forEach(item => {
        if (item.runType) {
          this.$set(item, 'duration', diffSecond(item.time))
        }
      })
    },
    // 获取分页数据
    // onLoadData (index, done) {
    //   setTimeout(() => {
    //     if (this.listData) {
    //       this.listData.push({}, {}, {}, {}, {}, {})
    //       done()
    //     }
    //   }, 2000)
    // },
    // 跳转详情传值
    routerTo (data) {
      // console.log(deviceNumber)
      this.$router.push({
        path: 'online-process/online-process-detail',
        query: {
          deviceId: data.deviceId,
          boxId: data.boxId,
          deviceName: `${data.deviceType}(${data.deviceNumber})`,
          location: this.queryParams.location.label
        }
      })
    },

    // 获取列表数据
    getListData () {
      const params = {
        searchBy: this.searchBy || undefined,
        keyword: this.keyword || undefined,
        level: this.queryParams.location.level || undefined,
        positionId: this.queryParams.location.id || undefined,
        deviceType: this.queryParams.deviceType || undefined
      }
      this.isNone = false
      this.closeUbscribeTopic()
      getProcessingList(params).then(res => {
        if (res.data.length) {
          res.data.forEach(item => {
            if (item.runType) {
              item.time = moment(item.time).format('YYYY-MM-DD HH:mm:ss')
              console.log(item.time)
              item.duration = diffSecond(item.time)
            }
            item.deviceType = this.$utils.label(item.deviceType)
            item.deviceNumber = this.$utils.label(item.deviceNumber)
            item.productNamesAndNumbers = this.$utils.label(item.productNamesAndNumbers)
            const processPlanningName = this.$utils.label(item.processPlanningName)
            item.processPlanningName = (_.isNil(item.processPlanningSort) || item.processPlanningSort === -1) ? processPlanningName : `${item.processPlanningSort + 1}-${processPlanningName}`
            item.programNumber = this.$utils.label(item.programNumber)
          })
          this.listData = res.data
        } else {
          this.listData = []
          this.isNone = true
        }
      }).then(() => {
        this.onConnect()
      }).catch(() => {
        console.log('获取数据失败')
      })
    },
    // 搜索
    inputSearch (item, searchVal) {
      this.searchBy = item.id
      this.keyword = searchVal
      this.getListData()
    },
    // 清空
    clearSearchVal () {
      this.keyword = ''
      this.searchBy = ''
      this.getListData()
    },
    // 判空
    isNullOrEmpty (strVal) {
      if (strVal === '' || strVal === null || strVal === undefined) {
        if (strVal === false) {
          return false
        } else {
          return true
        }
      } else {
        return false
      }
    },
    /**
     * 选择组织机构树节点
     * @param {number} val
     */
    _changeTreeNode: function (val) {
      if (val.id && val.label && val.hash) {
        this.queryParams.location.id = val.id
        this.queryParams.location.level = val.level
        this.queryParams.location.label = val.label
        this.queryParams.location.hash = val.hash
      } else {
        this.queryParams.location = {
          id: null,
          level: null,
          label: '',
          hash: ''
        }
      }
      if (this.isInit) {
        this.isInit = false
        this.getListData()
      }
    },
    /**
     * 重置查询条件
     */
    resetSearch () {
      this.queryParams.deviceType = null
      this.queryParams.location = Object.assign({}, this.locationOptions[0])
      this.$refs.selectTree.setValue(this.queryParams.location)
      this._changeTreeNode(this.queryParams.location)
    },
    // 查询按钮
    submit () {
      this.getListData()
    },
    // 计算运行时间
    getTime (time, runType) {
      if (!runType) {
        return
      }
      if (_.isNil(time)) {
        time = 0
      }
      const days = Math.floor(time / (24 * 3600))
      const leave1 = time % (24 * 3600)
      const hours = Math.floor(leave1 / (3600))

      const leave2 = leave1 % (3600)
      const minutes = Math.floor(leave2 / (60))

      const leave3 = leave2 % (60)
      const seconds = Math.round(leave3)
      const times = (days === 0 ? '' : (days + '天')) + (hours === 0 ? '' : (hours + '时')) + (minutes === 0 ? '' : (minutes + '分')) + (seconds === 0 ? '' : (seconds + '秒'))

      // console.log(times)
      return times !== '' ? times : '暂无'
    }
  },
  components: {
    SelectInput,
    SelectTree
  }
}
</script>

<style scoped lang="stylus">
  .none-tips{
    color #999999
    line-height 3
  }
  .font-size-16 {
    font-size 16px
  }
  .font-size-14 {
    font-size 14px
  }
  .scroll-area-h{
    height calc(100% - 144px)
  }
  .item-box{
    padding 0 10px 20px
  }
  .list-item{
    border-radius 6px
    overflow hidden
  }
  .item-title{
    background-color $secondary /* 不支持线性的时候显示 */
    background-image linear-gradient(to right, $secondary,#51a8e1, $primary);
    padding 5px 20px
  }
  .content{
    padding 0 20px
    color #333333
  }
  .legend{
    padding 20px 0
  }
  .product{
    width 17%
    min-width 40px
    margin 0 10px
  }
  .toolbar{
    padding 0
  }
  .right-side{
    margin-left auto
    padding 0 15px
  }
</style>
